package com.example.mainexam2022110341

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File
import java.io.InputStreamReader
import java.io.OutputStreamWriter

object DateEventManager {

    private val eventMap: MutableMap<String, MutableList<DateEvent>> = mutableMapOf()
    private val gson = Gson()
    private val fileName = "events.json"

    // 初始化方法
    fun initialize(context: Context) {
        Thread {
            loadEventsFromJson(context)
        }.start()
    }

    // 添加事件
    fun addEvent(event: DateEvent, context: Context) {
        val key = "${event.dateyear}-${event.datemonth}-${event.dateday}"
        if (eventMap.containsKey(key)) {
            eventMap[key]?.add(event)
        } else {
            eventMap[key] = mutableListOf(event)
        }
        saveEventsToJson(context)
    }

    // 获取事件列表
    fun getEvents(year: String, month: String, day: String): List<DateEvent>? {
        val key = "$year-$month-$day"
        return eventMap[key]
    }

    // 清除单个事件
    fun clearEvent(event: DateEvent, context: Context) {
        val key = "${event.dateyear}-${event.datemonth}-${event.dateday}"
        eventMap[key]?.remove(event)
        if (eventMap[key]?.isEmpty() == true) {
            eventMap.remove(key)
        }
        saveEventsToJson(context)
    }

    // 清除所有事件
    private fun clearAllEvent(context: Context) {
        eventMap.clear()
        saveEventsToJson(context)
    }

    // 保存事件到 JSON 文件
    private fun saveEventsToJson(context: Context) {
        val jsonString = gson.toJson(eventMap)
        val file = File(context.filesDir, fileName)
        OutputStreamWriter(file.outputStream()).use { it.write(jsonString) }
    }

    // 从 JSON 文件加载事件
    private fun loadEventsFromJson(context: Context) {
        val file = File(context.filesDir, fileName)
        if (file.exists()) {
            InputStreamReader(file.inputStream()).use { reader ->
                val type = object : TypeToken<MutableMap<String, MutableList<DateEvent>>>() {}.type
                val loadedMap: MutableMap<String, MutableList<DateEvent>> = gson.fromJson(reader, type)
                eventMap.putAll(loadedMap)
            }
        }
    }

}